package com.ruoyi.system.service.impl;

import com.ruoyi.IOT.requset.PointRequest;
import com.ruoyi.IOT.service.GatherService;
import com.ruoyi.IOT.service.ITVartriverService;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.TPoint;
import com.ruoyi.system.domain.TVartriver;
import com.ruoyi.system.mapper.TPointMapper;
import com.ruoyi.system.service.ITPointService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物联网节点 服务层实现
 *
 * @author ruoyi
 * @date 2019-09-19
 */
@Service
public class TPointServiceImpl implements ITPointService {
    @Autowired
    private TPointMapper tPointMapper;

    @Autowired
    private GatherService gatherService;

    @Autowired
    private ITVartriverService itVartriverService;

    /**
     * 查询物联网节点信息
     *
     * @param tpId 物联网节点ID
     * @return 物联网节点信息
     */
    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public TPoint selectTPointById(Integer tpId) {
        return tPointMapper.selectTPointById(tpId);
    }

    /**
     * 查询物联网节点列表
     *
     * @param tPoint 物联网节点信息
     * @return 物联网节点集合
     */
    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public List<TPoint> selectTPointList(TPoint tPoint) {
        return tPointMapper.selectTPointList(tPoint);
    }

    /**
     * 新增物联网节点
     *
     * @param tPoint 物联网节点信息
     * @return 结果
     */
    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public int insertTPoint(TPoint tPoint) {
        return tPointMapper.insertTPoint(tPoint);
    }

    /**
     * 修改物联网节点
     *
     * @param tPoint 物联网节点信息
     * @return 结果
     */
    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public int updateTPoint(TPoint tPoint) {
        return tPointMapper.updateTPoint(tPoint);
    }


    /**
     * 查询部门是否存在设备
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @DataSource(value = DataSourceType.SLAVE)
    public boolean checkPointExistDevice(Long deptId) {
        int result = tPointMapper.checkPointExistDevice(deptId);
        return result > 0 ? true : false;
    }

    //*********************************关联业务***************************************

    /**
     * 删除物联网节点对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public int deleteTPointByIds(String ids) {
        return tPointMapper.deleteTPointByIds(Convert.toStrArray(ids));
    }

    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public AjaxResult remove(Long tpId, String uuid) {
        if (checkPointExistDevice(tpId)) {
            return AjaxResult.warn("存在设备,不允许删除");
        }
        tPointMapper.deleteTPointByUuid(uuid);
        return null;
    }

    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public int edit(SysDept dept) {
        TPoint point = tPointMapper.selectTPointByUuid(dept.getUuid());
        if (point != null && point.getTpId() != null) {
            point.setUuid(dept.getUuid());
            point.setTpName(dept.getDeptName());
            point.setTpIndex(Integer.parseInt(dept.getOrderNum()));

            return tPointMapper.updateTPointByUuid(point);
        } else {
            return 0;
        }

    }

    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public int add(SysDept dept, SysDept parent) {
        //班组
        if ("0,100".equals(parent.getAncestors())) {
            TPoint point = new TPoint();
            point.setUuid(dept.getUuid());
            point.setTpName(dept.getDeptName());
            point.setTpPid(new Long(0));
            point.setTpType(new Long(1));
            point.setTpIndex(Integer.parseInt(dept.getOrderNum()));
            tPointMapper.insertTPoint(point);
        } else if ("0,100,101".equals(parent.getAncestors())) {
            TPoint pp = tPointMapper.selectTPointByUuid(parent.getUuid());
            TPoint point = new TPoint();
            point.setUuid(dept.getUuid());
            point.setTpPid(pp.getTpId());
            point.setTpName(dept.getDeptName());
            point.setTpIndex(Integer.parseInt(dept.getOrderNum()));
            point.setTpType(new Long(2));
            tPointMapper.insertTPoint(point);
        }
        return 0;
    }

    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public Map<String, Object> listSensorChartInfo(SysDept d) {
        Map<String, Object> map = new HashMap<>();
        map = fillChannels(map);
        TPoint point = tPointMapper.selectTPointByUuid(d.getUuid());//温室
        /*温室下面的设备*/

        if (point != null) {
            TPoint temp = new TPoint();
            temp.setTpPid(point.getTpId());
            List<TPoint> tPoints = tPointMapper.selectTPointList(temp);
            if (tPoints != null && tPoints.size() > 0) {
                point = tPoints.get(0);
                String deviceId = point.getDeviceId();
                List<Map<String, Object>> listSensorInfo = new ArrayList<>();


                //根据设备id 查询手动管理数据表
                TVartriver tVartriver = new TVartriver();
                tVartriver.setDeviceId(deviceId);
                List<TVartriver> tVartriverList = itVartriverService.selectTVartriverList(tVartriver);

                PointRequest pr = new PointRequest();
                pr.setDeviceId(deviceId);
                List<Map<String, Object>> real = gatherService.listSensorInfoFirst(pr);


                if (tVartriverList.isEmpty()) {
                    //未进行手动管理 返回原数据
                    listSensorInfo = gatherService.listSensorInfoFirst(pr);
                } else {
                    Map rv = new HashMap();
                    if (real != null && real.size() > 0) {
                        rv = real.get(0);
                    }

                    //该设备有手动管理数据
                    TVartriver sv = tVartriverList.get(0);
                    //该设备有手动管理数据
                    if ("1".equals(sv.getManualControl())) {
                        //手动管理 返回表中数据

                        map.put("Channel1", StringUtils.isEmpty(sv.getChannel1()) ? rv.get("Channel1") : sv.getChannel1());
                        map.put("Channel2", StringUtils.isEmpty(sv.getChannel2()) ? rv.get("Channel2") : sv.getChannel2());
                        map.put("Channel3", StringUtils.isEmpty(sv.getChannel3()) ? rv.get("Channel3") : sv.getChannel3());
                        map.put("Channel4", StringUtils.isEmpty(sv.getChannel4()) ? rv.get("Channel4") : sv.getChannel4());
                        map.put("Channel5", StringUtils.isEmpty(sv.getChannel5()) ? rv.get("Channel5") : sv.getChannel5());
                        map.put("Channel6", StringUtils.isEmpty(sv.getChannel6()) ? rv.get("Channel6") : sv.getChannel6());
                        map.put("Channel7", StringUtils.isEmpty(sv.getChannel7()) ? rv.get("Channel7") : sv.getChannel7());
                        map.put("Channel8", StringUtils.isEmpty(sv.getChannel8()) ? rv.get("Channel8") : sv.getChannel8());
                        map.put("Channel17", StringUtils.isEmpty(sv.getChannel17()) ? rv.get("Channel17") : sv.getChannel17());

                        map.put("infoDataTime", sv.getInfoDataTime());
                        listSensorInfo.add(map);

                    } else if ("0".equals(tVartriverList.get(0).getManualControl())) {
                        //自动管理 返回原数据
                        listSensorInfo = gatherService.listSensorInfoFirst(pr);
                    }
                }


                if (listSensorInfo.size() > 0) {
                    map = listSensorInfo.get(0);
                }
                map.put("tp_id", point.getTpId());
            }

        }

        return map;
    }

    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public Map getWeatherInfo() {
        Map<String, Object> map = new HashMap<>();
        map = fillChannels(map);
        TPoint temp = new TPoint();
        temp.setTpPid(new Long(300));
        List<TPoint> tPoints = tPointMapper.selectTPointList(temp);
        if (tPoints != null && tPoints.size() > 0) {
            TPoint point = tPoints.get(0);


            String deviceId = point.getDeviceId();

            PointRequest pr = new PointRequest();
            pr.setDeviceId(deviceId);

//            List<Map<String, Object>> listSensorInfo = gatherService.listSensorInfoFirst(pr);
            List<Map<String, Object>> listSensorInfo = new ArrayList<>();


            //根据设备id 查询手动管理数据表
            TVartriver tVartriver = new TVartriver();
            tVartriver.setDeviceId(deviceId);
            List<TVartriver> tVartriverList = itVartriverService.selectTVartriverList(tVartriver);

            List<Map<String, Object>> real = gatherService.listSensorInfoFirst(pr);

            if (tVartriverList.isEmpty()) {
                //未进行手动管理 返回原数据
                listSensorInfo = gatherService.listSensorInfoFirst(pr);
            } else {
                Map rv = new HashMap();
                if (real != null && real.size() > 0) {
                    rv = real.get(0);
                }
                TVartriver sv = tVartriverList.get(0);
                //该设备有手动管理数据
                if ("1".equals(sv.getManualControl())) {
                    //手动管理 返回表中数据

                    map.put("Channel1", StringUtils.isEmpty(sv.getChannel1()) ? rv.get("Channel1") : sv.getChannel1());
                    map.put("Channel2", StringUtils.isEmpty(sv.getChannel2()) ? rv.get("Channel2") : sv.getChannel2());
                    map.put("Channel3", StringUtils.isEmpty(sv.getChannel3()) ? rv.get("Channel3") : sv.getChannel3());
                    map.put("Channel4", StringUtils.isEmpty(sv.getChannel4()) ? rv.get("Channel4") : sv.getChannel4());
                    map.put("Channel5", StringUtils.isEmpty(sv.getChannel5()) ? rv.get("Channel5") : sv.getChannel5());
                    map.put("Channel6", StringUtils.isEmpty(sv.getChannel6()) ? rv.get("Channel6") : sv.getChannel6());
                    map.put("Channel7", StringUtils.isEmpty(sv.getChannel7()) ? rv.get("Channel7") : sv.getChannel7());
                    map.put("Channel8", StringUtils.isEmpty(sv.getChannel8()) ? rv.get("Channel8") : sv.getChannel8());
                    map.put("Channel17", StringUtils.isEmpty(sv.getChannel17()) ? rv.get("Channel17") : sv.getChannel17());

                    map.put("infoDataTime", sv.getInfoDataTime());
                    listSensorInfo.add(map);

                } else if ("0".equals(sv.getManualControl())) {
                    //自动管理 返回原数据
                    listSensorInfo = gatherService.listSensorInfoFirst(pr);
                }
            }

            if (listSensorInfo.size() > 0)
                map = listSensorInfo.get(0);
        }
        return map;
    }

    private Map fillChannels(Map m) {
        for (int i = 1; i < 51; i++) {
            m.put("Channel" + i, "--");
        }
        return m;
    }

    public void calcFailData(List<SysDept> result)throws Exception {
        /*正确的数组*/
        List<SysDept> right = new ArrayList<>();
        /*错误数组*/
        List<SysDept> wrong = new ArrayList<>();
        //找出时间不对的-没有时间 或者时间超过两个小时
        for (SysDept room : result) {
            Map cg = room.getParams();
            Object time = cg.get("infoDataTime");
            if (time != null) {
                int hours = DateUtils.getDiffHours(time);
                if (hours > 2) {
                    wrong.add(room);
                } else {
                    right.add(room);
                }
            }
        }
        /*求平均值*/
        double channel1 = new Double(0);
        double channel2 = new Double(0);
        double channel3 = new Double(0);
        double channel4 = new Double(0);
        double channel5 = new Double(0);
        double channel6 = new Double(0);
        double channel7 = new Double(0);
        double channel8 = new Double(0);
        Map righ = new HashMap();
        for (SysDept r : right) {
            //空气温度
            channel1 += Double.parseDouble("" + r.getParams().get("Channel1"));
            channel2 += Double.parseDouble("" + r.getParams().get("Channel2"));
            channel3 += Double.parseDouble("" + r.getParams().get("Channel3"));
            channel4 += Double.parseDouble("" + r.getParams().get("Channel4"));
            channel5 += Double.parseDouble("" + r.getParams().get("Channel5"));
            channel6 += Double.parseDouble("" + r.getParams().get("Channel6"));
            channel7 += Double.parseDouble("" + r.getParams().get("Channel7"));
            channel8 += Double.parseDouble("" + r.getParams().get("Channel8"));

        }

        channel1 = channel1 / right.size();
        channel2 = channel2 / right.size();
        channel3 = channel3 / right.size();
        channel4 = channel4 / right.size();
        channel5 = channel5 / right.size();
        channel6 = channel6 / right.size();
        channel7 = channel7 / right.size();
        channel8 = channel8 / right.size();



        for (SysDept r : wrong) {
            r.getParams().put("Channel1", fun2(channel1));
            r.getParams().put("Channel2", fun2(channel2));
            r.getParams().put("Channel3", fun2(channel3));
            r.getParams().put("Channel4", fun2(channel4));
            r.getParams().put("Channel5", fun2(channel5));
            r.getParams().put("Channel6", fun2(channel6));
            r.getParams().put("Channel7", fun2(channel7));
            r.getParams().put("Channel8", fun2(channel8));
        }


    }

    public String fun2(Double d) throws Exception {
        DecimalFormat df = new DecimalFormat("#.0");
        return df.format(d);
    }

}
